#include "Player.h"

Player::Player(PlayerPosition pPos, 
			   PlayerInput *pInput, 
			   VisualObject *rep, 
			   Playfield &iPlayfield,
			   GameMode &gm):
	playerinput(pInput),
	playerposition(pPos),
	playfield(iPlayfield),
	gamemode(gm)
{
	representation = rep;
	representation->loadImage("images/pallet.png");
	
	speed = 85.0f;
	targetReached = false;
	//set position
	reset();
	targetX = x;
	if(playerposition == PP_LEFT)
		realX = -getWidth()/2;
	if(playerposition == PP_RIGHT)
		realX = playfield.getWidth() + getWidth()/2;
}

Player::~Player(void)
{
}


void Player::getReadyForDraw()
{
	y = static_cast<int>(realY);
	x = static_cast<int>(realX);

	// we need to calculate offsets!
	representation->setOffsetX(x - getWidth()/2);
	representation->setOffsetY(y - getHeight()/2);


}

void Player::update(const double time)
{
	if(gamemode == GM_INTRO)
		updateIntro(time);
	if(gamemode == GM_PLAY)
		updatePlay(time);
}

void Player::updateIntro(const double time)
{
	const double movespeed = 15.0;
	double directionalSpeed;

	if(playerposition == PP_LEFT)
		directionalSpeed = movespeed;
	else
		directionalSpeed = -movespeed;

	realX += directionalSpeed*time;

	// now see if we've gone too far
	if((realX > targetX && playerposition == PP_LEFT) ||
		(realX < targetX && playerposition == PP_RIGHT))
	{
		realX = targetX;
		targetReached = true;
	}
}

bool Player::canComeOutOfIntro()
{
	return targetReached;
}
void Player::updatePlay(const double time)
{

	if(playerinput->goingDown())
	{
		realY += time*speed;
	}

	if(playerinput->goingUp())
	{
		realY -= time*speed;
	}

	// hitting the upper boundary of the screen
	if(realY < getHeight()/2)
	{
		y = getHeight()/2;
		realY = y;
		
	}

	// hitting the lower boundary of the screen
	if(realY + getHeight()/2 > playfield.getHeight())
	{
		y = playfield.getHeight()- getHeight()/2;
		realY = y;

	}

}

void Player::reset()
{
	if(playerposition == PP_LEFT)
	{
		realX = 30;
		realY = playfield.getHeight()/2;
	}
	else if(playerposition == PP_RIGHT)
	{
		realX = playfield.getWidth() - 30;
		realY = playfield.getHeight()/2;
	}

	x = static_cast<int>(realX);
	y = static_cast<int>(realY);

}

void Player::increaseSpeed()
{
	if(speed < 200)
		speed *= 1.09;
}

void Player::scorePoint()
{
	score++;
}
